<?php
namespace app\modules\backend\controllers;


use app\models\Shop;
use app\models\Good;
use app\models\Area;
use app\models\Message;
use app\models\Customer;
use app\tools\WxPay;
use app\tools\Re;
use app\models\OrderInfo;
use Yii;

class OrderController extends BaseController
{
  public $state_name_arr = ['待支付','已支付','待退款','已退款','退款失败','服务中','已完成'];
  public $refund_state_name_arr = ['待审核','退款成功','退款失败'];

  //订单列表
  public function actionOrderList() {
    $page = Yii::$app->request->post('page', 0);
    $page_size = Yii::$app->request->post('page_size', 20);
    $shop_id = Yii::$app->request->post('shop_id', 0);
    $good_id = Yii::$app->request->post('good_id', 0);
    $order_sn = Yii::$app->request->post('order_sn', '');
    $name = Yii::$app->request->post('name', '');
    $phone = Yii::$app->request->post('phone', '');
    $state = Yii::$app->request->post('state', -2);
    $area_id = Yii::$app->request->post('area_id', 0);
    $date_range = Yii::$app->request->post('date_range', '');
    $over_time = time() - 7200;
    $query = OrderInfo::find()
      ->leftJoin(Shop::tableName(), 'order_info.shop_id = shop.id')
      ->leftJoin(Customer::tableName(), 'order_info.customer_id = customer.id')
      ->where(['order_type' => 1]);
    if (Yii::$app->user->identity->shop_id) {//门店人员只读取本门店数据
      $query->andWhere(['order_info.shop_id' => Yii::$app->user->identity->shop_id]);
    }
    if ($shop_id) {
      $query->andWhere(['order_info.shop_id' => $shop_id]);
    }
    if ($good_id) {
      $query->andWhere(['order_info.good_id' => $good_id]);
    }
    if ($order_sn) {
      $query->andWhere(['like', 'order_info.order_sn', $order_sn]);
    }
    if ($name) {
      $query->andWhere(['like', 'customer.name', $name]);
    }
    if ($phone) {
      $query->andWhere(['like', 'customer.phone', $phone]);
    }
    if ($state > -2) {
      if ($state == -1) {
        $query->andWhere("state = 0 and order_info.created_at < '$over_time'");
      } else if ($state == 0) {
        $query->andWhere("state = 0 and order_info.created_at >= '$over_time'");
      } else {
        $query->andWhere(['order_info.state' => $state]);
      }
    }
    if ($area_id) {
      $query->andWhere(['shop.area_id' => $area_id]);
    }
    if ($date_range) {
      $data_arr = explode("-", $date_range);
      $start_at = $data_arr[0];
      $end_at = $data_arr[1] + 86400;
      $query->andWhere("order_info.created_at >= '$start_at' and order_info.created_at <= '$end_at'");
    }
    $query->groupBy('order_info.id');
    $count_query = clone $query;
    $list = $query->orderBy('order_info.created_at desc')->limit($page_size)->offset($page_size*$page)->all();
    $data = [];
    if ($list) {
      foreach ($list as $v) {
        $order_state = $v->state;
        if ($v->state == 0 && $v->created_at+7200<time()) {
          $order_state = -1;
        }
        $data[] = [
          'id' => $v->id,
          'shop_name' => $v->shop->name,
          'order_sn' => $v->order_sn,
          'good_name' => $v->good->name,
          'name' => $v->customer->name,
          'phone' => $v->customer->phone,
          'created_time' => date("Y-m-d H:i:s", $v->created_at),
          'pay_time' => $v->pay_at ? date("Y-m-d H:i:s", $v->pay_at) : '',
          'state' => $order_state,
          'state_name' => $order_state == -1 ? '已过期' : $this->state_name_arr[$v->state],
          'money' => floatval($v->money),
        ];
      }
    }
    return Re::data([
      'data' => $data,
      'totalPage' => $count_query->count(),
      'currentPage' => $page,
      'perPage' => OrderInfo::PAGE_SIZE
    ]);
  }

  //订单详情
  public function actionOrderDetail() {
    $id = Yii::$app->request->post('id', 0);
    $order = OrderInfo::findOne($id);
    if (!$order) {
      return Re::data(null, '订单信息读取失败', Re::ERROR);
    }
    $order_state = $order->state;
    if ($order->state == 0 && $order->created_at+7200<time()) {
      $order_state = -1;
    }
    $order_data = [
      'id' => $order->id,
      'shop_name' => $order->shop->name,
      'order_sn' => $order->order_sn,
      'good_name' => $order->good->name,
      'name' => $order->customer->name,
      'phone' => $order->customer->phone,
      'service_address' => $order->service_address,
      'unit_price' => $order->unit_price,
      'num' => $order->num,
      'money' => floatval($order->money),
      'remark' => $order->remark,
      'state' => $order_state,
      'state_name' => $order_state == -1 ? '已过期' : $this->state_name_arr[$order->state],
      'created_time' => date("Y-m-d H:i:s", $order->created_at),
      'pay_time' => $order->pay_at ? date("Y-m-d H:i:s", $order->pay_at) : '',
      'service_start_time' => $order->service_start_at ? date("Y-m-d H:i:s", $order->service_start_at) : '',
      'service_start_img' => $order->service_start_img,
      'service_finsh_time' => $order->service_finsh_at ? date("Y-m-d H:i:s", $order->service_finsh_at) : '',
      'service_finsh_img' => $order->service_finsh_img
    ];
    $order_refund_data = [];
    $order_refund = OrderInfo::find()->where(['relate_id' => $id, 'order_type' => 2])->one();
    if ($order_refund) {
      $order_refund_data = [
        'refund_remark' => $order_refund->refund_remark,
        'refund_time' => date("Y-m-d H:i:s", $order_refund->created_at),
        'refund_audit_state' => $order_refund->refund_audit_state,
        'refund_audit_state_name' => $order_refund->refund_audit_state ? ($order_refund->refund_audit_state == 1 ? '已同意' : '已拒绝') : '未审核',
        'refund_audit_remark' => $order_refund->refund_audit_remark,
        'refund_audit_admin' => $order_refund->refund_audit_admin,
        'refund_audit_admin_name' => $order_refund->refund_audit_admin ? $order_refund->admin->name : '',
        'refund_audit_time' => $order_refund->refund_audit_at ? date("Y-m-d H:i:s", $order_refund->refund_audit_at) : '',
      ];
    }
    return Re::data(['order_info' => $order_data, 'order_refund' => $order_refund_data]);
  }

  //退款列表
  public function actionRefundList(){
    $page = Yii::$app->request->post('page', 0);
    $shop_id = Yii::$app->request->post('shop_id', 0);
    $audit_state = Yii::$app->request->post('audit_state', -2);
    $name = Yii::$app->request->post('name', '');
    $phone = Yii::$app->request->post('phone', '');
    $date_range = Yii::$app->request->post('date_range', '');
    $pageSize = Yii::$app->request->post('page_size', 20);
    $query = OrderInfo::find()
      ->leftJoin(Customer::tableName(), 'order_info.customer_id = customer.id')
      ->where(['order_info.order_type' => 2]);
    if (Yii::$app->user->identity->shop_id) {//门店人员只读取本门店数据
      $shop_id = Yii::$app->user->identity->shop_id;
    }
    if ($shop_id) {
      $query->andWhere(['order_info.shop_id' => $shop_id]);
    }
    if ($name) {
      $query->andWhere(['like', 'customer.name', $name]);
    }
    if ($phone) {
      $query->andWhere(['like', 'customer.phone', $phone]);
    }
    if ($audit_state > -1) {
      $query->andWhere(['order_info.refund_audit_state' => $audit_state]);
    }
    if ($date_range) {
      $data_arr = explode("-", $date_range);
      $start_at = $data_arr[0];
      $end_at = $data_arr[1] + 86400;
      $query->andWhere("order_info.created_at >= '$start_at' and order_info.created_at <= '$end_at'");
    }
    $list = $query->orderBy("order_info.created_at desc")->limit($pageSize)->offset($page*$pageSize)->all();
    $data = [];
    if ($list) {
      foreach ($list as $v) {
        $order = OrderInfo::findOne($v->relate_id);
        $data[] = [
          'id' => $order->id,
          'customer_id' => $order->customer_id,
          'name' => $order->customer->name,
          'phone' => $order->customer->phone,
          'shop_name' => $order->shop->name,
          'good_name' => $order->good->name,
          'created_time' => date("Y-m-d H:i:s", $v->created_at),
          'order_sn' => $order->order_sn,
          'money' => $order->money,
          'refund_remark' => $v->refund_remark,
          'refund_audit_state' => $v->refund_audit_state,
          'refund_audit_state_name' => $this->refund_state_name_arr[$v->refund_audit_state],
          'refund_audit_remark' => $v->refund_audit_remark,
          'refund_audit_admin' => $v->refund_audit_admin,
          'refund_audit_admin_name' => $v->refund_audit_admin ? $v->admin->name : '',
          'refund_audit_time' => $v->refund_audit_at ? date("Y-m-d H:i:s", $v->refund_audit_at) : ''
        ];
      }
    }
    return Re::data([
      'data' => $data,
      'totalPage' => $query->count(),
      'currentPage' => $page,
      'perPage' => $pageSize?:OrderInfo::PAGE_SIZE
    ]);
  }

  //退款审核
  public function actionAuditOrderRefund() {
    $id = Yii::$app->request->post('id', 0);
    $refund_audit_state = Yii::$app->request->post('refund_audit_state', 0);
    $refund_audit_remark = Yii::$app->request->post('refund_audit_remark', '');
    $order = OrderInfo::findOne($id);
    if (!$order) {
      return Re::data(null, '订单信息读取失败', Re::ERROR);
    }
    $order_refund = OrderInfo::find()->where(['relate_id' => $id])->one();
    if (!$order_refund) {
      return Re::data(null, '退款信息读取失败', Re::ERROR);
    }
    if ($refund_audit_state == 1) {
      $res = WxPay::refund($order, $order_refund->money);
      if (!($res->return_code == 'SUCCESS' && $res->result_code == 'SUCCESS')) {
        return Re::data(null, $res->err_code_des, Re::ERROR);
      }
    }
    $order->state = $refund_audit_state == 1 ? 3 : 4;
    $order->save();

    $order_refund->refund_audit_state = $refund_audit_state;
    $order_refund->refund_audit_admin = Yii::$app->user->id;
    $order_refund->refund_audit_remark = $refund_audit_remark;
    $order_refund->refund_audit_at = time();
    $order_refund->save();

    $refund_audit_res = $refund_audit_state == 1 ? '审核通过' : '审核未通过, 原因：'.$refund_audit_remark;
    $message = new Message();
    $message->shop_id = $order->shop_id;
    $message->customer_id = $order->customer_id;
    $message->title = '订单退款审核';
    $message->content = '订单'.$order->order_sn.$refund_audit_res;
    $message->created_at = time();
    if (!$message->save()) {
      return Re::data(null, $message->showErrors(), Re::ERROR);
    }
    return Re::data();
  }

  //订单服务状态变更
  public function actionChangeOrderServiceState(){
    $id = Yii::$app->request->post('id', 0);
    $state = Yii::$app->request->post('state', 5);
    $img = Yii::$app->request->post('img', '');
    $order = OrderInfo::findOne($id);
    if (empty($order)) {
      return Re::data(null, '订单信息读取失败', Re::ERROR);
    }
    $order->state = $state;
    if ($state == 5) {
      $order->service_start_at = time();
      $order->service_start_img = $img;
    } else {
      $order->service_finsh_at = time();
      $order->service_finsh_img = $img;
    }
    $order->save();
    
    //保存消息
    $message = new Message();
    $message->shop_id = $order->shop_id;
    $message->customer_id = $order->customer_id;
    $message->title = $state == 5 ? '订单服务开始' : '订单服务完成';
    $message->content = '订单编号：'.$order->order_sn.($state == 5 ? '已开始服务' : '已完成服务');
    $message->created_at = time();
    $message->save();
    return Re::data();
  }
}
